/**
 * contact控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.controller;


import com.sxf.crm.entity.Contact;
import com.sxf.crm.entity.Department;
import com.sxf.crm.dto.ContactDTO;
import com.sxf.crm.dto.ContactRequest;
import com.sxf.crm.dto.UpdateContactRequest;
import com.sxf.crm.service.ContactService;
import com.sxf.crm.service.ContactDepartmentService;
import com.sxf.crm.service.DepartmentService;
import com.sxf.crm.util.SecurityUtils;

import org.springframework.transaction.annotation.Transactional;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/contacts")
@RequiredArgsConstructor
@Slf4j
public class ContactController {
    private static final Logger logger = LoggerFactory.getLogger(ContactController.class);
    private final ContactService contactService;
    private final ContactDepartmentService contactDepartmentService;
    private final DepartmentService departmentService;

    @GetMapping
    @PreAuthorize("hasAuthority('contact:list')")
    public ResponseEntity<Page<ContactDTO>> getContacts(
            @RequestParam(required = false) String name,
            Pageable pageable) {
        Page<Contact> contacts = contactService.getContacts(name, pageable);
        Page<ContactDTO> dtos = contacts.map(ContactDTO::fromEntity);
        return ResponseEntity.ok(dtos);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('contact:view')")
    public ResponseEntity<ContactDTO> getContact(@PathVariable Long id) {
        Contact contact = contactService.getContact(id);
        return ResponseEntity.ok(ContactDTO.fromEntity(contact));
    }

    @PostMapping
    @PreAuthorize("hasAuthority('contact:create')")
    public ResponseEntity<ContactDTO> createContact(@RequestBody ContactRequest request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        
        logger.debug("创建新联系人: 当前用户ID={}, 用户名={}, 请求参数={}", currentUserId, currentUsername,request);
        
        Contact created = contactService.createContact(request,currentUserId);
        return ResponseEntity.ok(ContactDTO.fromEntity(created));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('contact:update')")
    @Transactional
    public ResponseEntity<ContactDTO> updateContact(
            @PathVariable Long id,
            @RequestBody UpdateContactRequest request) {

        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        
        request.setId(id);
        logger.debug("更新联系人信息: 当前用户ID={}, 用户名={}, 请求参数={}", currentUserId, currentUsername,request);

        // 更新联系人基本信息
        Contact contact = contactService.updateContact(request.toContact(),currentUserId);
            
        // 处理部门关联关系
        if (request.getDepartmentIds() != null && !request.getDepartmentIds().isEmpty()) {
            // 1. 先删除旧的关联关系
            contactService.clearContactDepartments(id,currentUserId);
            
            // 2. 创建新的关联关系
            List<Department> departments = departmentService.getDepartmentsByIds(request.getDepartmentIds());
            contactDepartmentService.createContactDepartments(contact, departments);
        }
        
        // 刷新联系人数据，确保获取最新的关联数据
        contact = contactService.getContact(id);
        
        return ResponseEntity.ok(ContactDTO.fromEntity(contact));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('contact:delete')")
    public ResponseEntity<Void> deleteContact(@PathVariable Long id) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        
        logger.debug("删除联系人: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        
        contactService.deleteContact(id,currentUserId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/customer/{customerId}")
    @PreAuthorize("hasAuthority('contact:list')")
    public ResponseEntity<Page<Contact>> getCustomerContacts(
            @PathVariable Long customerId,
            Pageable pageable) {
        return ResponseEntity.ok(contactService.getCustomerContacts(customerId, pageable));
    }

    @PostMapping("/{id}/departments")
    @PreAuthorize("hasAuthority('contact:edit')")
    public ResponseEntity<Void> addContactDepartment(
            @PathVariable Long id,
            @RequestParam Long departmentId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        
        logger.debug("为联系人添加部门关联: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        
        contactService.addContactDepartment(id, departmentId,currentUserId);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}/departments/{departmentId}")
    @PreAuthorize("hasAuthority('contact:edit')")
    public ResponseEntity<Void> removeContactDepartment(
            @PathVariable Long id,
            @PathVariable Long departmentId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        
        logger.debug("移除联系人的部门关联: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        
        contactService.removeContactDepartment(id, departmentId,currentUserId);
        return ResponseEntity.ok().build();
    }
}
